package net.maku.kyy.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import net.maku.kyy.entity.KyyGameEntity;
import net.maku.kyy.service.KyyGameService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class UpdateDataTask {

    private static final String API_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxce48819f76ff62fa&secret=0732d8c146109f3caabcd69ca769a92b";

    private static final String API_URL = "https://api.weixin.qq.com/wxa/servicemarket/game/getminigamecpslist?access_token=";

    private final KyyGameService kyyGameService;

    public UpdateDataTask(KyyGameService kyyGameService) {
        this.kyyGameService = kyyGameService;
    }


    public void run(String params) throws InterruptedException {
        log.info("正在更新数据。", params);
        try {

            String tokenData = sendGETRequest(API_TOKEN);
            JSONObject tokenParse = JSONObject.parseObject(tokenData);
            System.out.println(tokenParse);
            String token = tokenParse.getString("access_token");

            String next_offset =null;
            Boolean has_next =true;

            while (has_next){
                // 发送POST请求并获取响应数据
                String responseData = sendPostRequest(API_URL + token,next_offset);
                // 解析JSON数据
                JSONObject gameObject = JSONObject.parseObject(responseData);
                if(gameObject==null){
                    return;
                }
                JSONArray app_list = gameObject.getJSONArray("app_list");
                next_offset =gameObject.getString("next_offset");
                has_next =gameObject.getBoolean("has_next");
                List<KyyGameEntity> allData = kyyGameService.getAll();
                if (app_list != null) {
                    List<KyyGameEntity> kyyGameEntityArrayList = new ArrayList<>();
                    for (Object appInfo : app_list) {
                        JSONObject itemData = JSONObject.parseObject(String.valueOf(appInfo));
                        KyyGameEntity kyyGameEntity = new KyyGameEntity();
                        String appid = itemData.getString("appid");
                        // 遍历allData，检查appid是否已存在
                        for (KyyGameEntity existingEntity : allData) {
                            if (existingEntity.getAppid()!=null&&existingEntity.getAppid().equals(appid)) {
                                kyyGameEntity.setId(existingEntity.getId());
                                break;
                            }
                        }
                        kyyGameEntity.setAppid(itemData.getString("appid"));
                        kyyGameEntity.setAppname(itemData.getString("appname"));
                        kyyGameEntity.setBriefIntro(itemData.getString("brief_intro"));
                        kyyGameEntity.setLogo(itemData.getString("logo"));
                        kyyGameEntity.setCategory2Id(itemData.getString("category_2_id"));
                        kyyGameEntity.setCategory2Name(itemData.getString("category_2_name"));
                        kyyGameEntity.setCategory3Id(itemData.getString("category_3_id"));
                        kyyGameEntity.setCategory3Name(itemData.getString("category_3_name"));
                        kyyGameEntity.setUserName(itemData.getString("user_name"));
                        kyyGameEntity.setBanner(itemData.getString("banner"));
                        kyyGameEntity.setVideoInfo(itemData.getString("video_info"));
                        kyyGameEntity.setPublicityImg(itemData.getString("publicity_img"));
                        kyyGameEntity.setLogoSquare(itemData.getString("logo_square"));
                        kyyGameEntity.setCpsPercent(itemData.getString("cps_percent"));
                        kyyGameEntity.setIsPcUnavailable(itemData.getString("is_pc_unavailable"));
                        kyyGameEntityArrayList.add(kyyGameEntity);
                    }
                    kyyGameService.saveOrUpdateBatch(kyyGameEntityArrayList);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("更新数据请求失败");
        }
    }


    private static String sendPostRequest(String url,String offset) throws IOException {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);

        // 设置请求头，这里设置为JSON格式请求（如果接口有此要求的话）
        httpPost.setHeader("Content-Type", "application/json");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("offset", offset);
        StringEntity entity = new StringEntity(jsonObject.toString(), ContentType.APPLICATION_JSON);
        httpPost.setEntity(entity);

        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();
        return EntityUtils.toString(responseEntity, "UTF-8");
    }

    private static String sendGETRequest(String url) throws IOException {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);

        // 设置请求头，这里设置为JSON格式请求（如果接口有此要求的话）
        httpGet.setHeader("Content-Type", "application/json");

        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity responseEntity = response.getEntity();
        return EntityUtils.toString(responseEntity, "UTF-8");
    }

}